<template>
    <div>
        <el-card class="box-card">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
                <el-breadcrumb-item>用户列表</el-breadcrumb-item>
            </el-breadcrumb>
            <div>
                <el-input placeholder="请输入要搜索的内容" v-model="searchInput" class="search-input" size="small"
                    @keyup.enter.native="search" clearable style="width: 400px;margin-bottom: 16px;">
                    <el-select v-model="searchType" slot="prepend" placeholder="请选择" class="search-select">
                        <el-option label="用户ID" value="0"></el-option>
                        <el-option label="用户名" value="1"></el-option>
                    </el-select>
                    <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
                </el-input>
            </div>

            <el-table :data="tableData" height="680" style="width: 100%" :border="true" :stripe="true"
                :header-cell-style="{ background: '#409EFF', color: '#FFF' }">
                <el-table-column width="100" label="userID" prop="userId"></el-table-column>
                <el-table-column label="用户名" prop="userName"></el-table-column>
                <el-table-column label="联系方式" prop="userTel"></el-table-column>
                <el-table-column label="注册时间" prop="registerTime"></el-table-column>
                <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                        <el-button size="small" @click="detailHandle(scope.row.userId)">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pageNumber" :page-sizes="[20, 40, 60, 80]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
            </el-pagination> -->

            <el-dialog title="用户详情" :visible.sync="dialogVisible" width="60%" top="5vh">
                <el-table :data="userInfo" style="width: 100%" :border="true" :stripe="true"
                    :header-cell-style="{ background: '#409EFF', color: '#FFF' }" height="300">
                    <el-table-column label="上上级用户" width="100">
                        <template slot-scope="scope">
                            {{ scope.row.grandsire == '' ? '暂无' : scope.row.grandsire.userName || '用户' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="上级用户" width="100">
                        <template slot-scope="scope">
                            {{ scope.row.pater == '' ? '暂无' : scope.row.pater.userName || '用户' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="账户积分" width="100">
                        <template slot-scope="scope">
                            {{ scope.row.surplusPoint || 0 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" width="100">
                        <template slot-scope="scope">
                            <el-tag v-if="scope.row.note == 1" type="success">会员</el-tag>
                            <el-tag v-else type="warning">游客</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="下级用户">
                        <el-table :data="LowerUser" style="width: 100%" :border="true" :stripe="true"
                            :header-cell-style="{ background: '#409EFF', color: '#FFF' }">
                            <el-table-column label="用户名">
                                <template slot-scope="scope">
                                    {{ scope.row.userName || '暂未设置' }}
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-table-column>
                    <!-- <el-table-column label="操作" width="100">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.surplusPoint > 0" size="small"
                                @click="sendHandle(scope.row.userId)">转赠</el-button>
                        </template>
                    </el-table-column> -->
                </el-table>

                <div class="titleBox">积分记录</div>
                <el-table :data="pointsList" style="width: 100%" :border="true" :stripe="true"
                    :header-cell-style="{ background: '#409EFF', color: '#FFF' }" height="300">
                    <el-table-column label="ID" prop="pointId" width="60"></el-table-column>
                    <el-table-column label="时间" prop="earnedDate" width="160"></el-table-column>
                    <el-table-column label="记录">
                        <template slot-scope="scope">
                            <template v-if="scope.row.pointType == 0">
                                订单编号：{{ scope.row.orderNum }}
                            </template>
                            <template v-if="scope.row.pointType == 2">
                                赠送给{{ scope.row.exportName }}（ID:{{ scope.row.exportId }}）
                            </template>
                            <template v-if="scope.row.pointType == 3">
                                {{ scope.row.sourcename }}（ID:{{ scope.row.source }}）赠送
                            </template>
                            <template v-if="scope.row.pointType == 1">
                                {{ scope.row.sourcename }}（ID:{{ scope.row.source }}）购买套餐返利
                            </template>

                        </template>
                    </el-table-column>
                    <el-table-column label="积分变动" width="100">
                        <template slot-scope="scope">
                            <template v-if="scope.row.pointType == 0 || scope.row.pointType == 2">
                                -
                            </template>
                            <template v-if="scope.row.pointType == 3 || scope.row.pointType == 1">
                                +
                            </template>
                            {{ scope.row.points }}
                        </template>
                    </el-table-column>
                    <el-table-column label="过期时间" prop="expiryDate" width="160"></el-table-column>
                    <el-table-column label="剩余积分" prop="surplusPoints" width="100"></el-table-column>
                    <el-table-column label="状态" width="120">
                        <template slot-scope="prop">

                            <el-tag v-if="(prop.row.pointType == 3 || prop.row.pointType == 1) && !prop.row.isPass"
                                type="success">未过期</el-tag>
                            <el-tag v-if="(prop.row.pointType == 3 || prop.row.pointType == 1) && prop.row.isPass"
                                type="danger">已过期</el-tag>


                        </template>
                    </el-table-column>
                </el-table>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">关 闭</el-button>
                </div>
            </el-dialog>


            <el-dialog title="转赠积分" :visible.sync="sendDia" @close="closeSend" width="500px">
                <el-form :model="form" :rules="rules" ref="form" label-width="80px">
                    <el-form-item label="赠送人ID">
                        <el-input v-model="form.senderId" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="受赠人ID" prop="receiverId">
                        <el-input v-model="form.receiverId" placeholder="请输入受赠人ID">
                            <el-button slot="append" @click="checkHandle(form.receiverId)">校验</el-button>
                        </el-input>
                        <div v-if="checkFlag == 1" class="checkSuccess">
                            <i class="el-icon-success"></i> 校验成功，用户名：{{ checkUserInfo.userName }}
                        </div>
                        <div v-if="checkFlag == 2" class="checkError">
                            <i class="el-icon-error"></i> 校验失败，用户存在，请检查受赠人ID
                        </div>
                    </el-form-item>
                    <el-form-item label="积分数" prop="point">
                        <el-input v-model="form.point" placeholder="请输入转赠积分数"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="closeSend">取 消</el-button>
                    <el-button @click="submitSend">确 定</el-button>
                </div>
            </el-dialog>

        </el-card>



    </div>
</template>

<script>
import { selectUser, listHigherUser, listLowerUser, increasePoints, listPoints, listRelations } from "network/user";

export default {
    data() {
        return {
            tableData: [],

            pageSize: 20,
            pageNumber: 1,
            totalCount: 0,
            pater: '',//上级信息
            grandsire: '',//上上级信息
            userInfo: [], // 用户信息
            LowerUser: [],//下级用户列表
            pointsList: [],//积分记录

            dialogVisible: false,
            sendDia: false,
            form: {
                senderId: '',
                receiverId: '',
                point: '',
            },
            rules: {
                receiverId: [
                    {
                        required: true,
                        message: "请输入受赠人ID",
                        trigger: "blur",
                    },
                ],
                point: [
                    {
                        required: true,
                        message: "请输入转赠积分数",
                        trigger: "blur",
                    },
                ],
            },

            searchType: '0',// 0 用户ID 1 用户名  
            searchInput: '',


            checkFlag: 0,  // 0 未校验  1 校验通过  2 校验失败
            checkUserInfo: {}
        };
    },
    comments: {},
    methods: {
        search() {
            console.log(this.searchType);
            console.log(this.searchInput);
            this.getList()

        },
        submitSend() {
            this.$refs.form.validate((valid) => {
                if (valid) {


                    if (this.checkFlag == 0) {
                        this.$message.warning('请先校验受赠人信息')
                        return
                    }

                    if (this.form.point > this.userInfo.surplusPoint) {
                        this.$message.warning('积分超出上限')
                        return
                    }
                    if (this.form.point < 1) {
                        this.$message.warning('请输入正确的积分数')
                        return
                    }
                    console.log(this.form);

                    // return


                    increasePoints(this.form)
                        .then((res) => {
                            if (res.flag) {
                                this.$message({
                                    type: "success",
                                    message: "操作成功",
                                });
                                this.detailHandle(this.form.senderId);
                                this.closeSend()
                            } else {
                                this.$message({
                                    message: "该用户暂不支持接受转赠",
                                    type: "warning",
                                });
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                } else {
                    return console.log("update Err");
                }
            });
        },
        closeSend() {
            this.form = {
                senderId: '',
                receiverId: '',
                point: '',
            }
            this.checkFlag = 0
            this.sendDia = false
        },
        sendHandle(id) {
            this.form.senderId = id
            this.sendDia = true
        },

        // 查看详情
        detailHandle(userId) {
            console.log(userId);
            // userId = 99828
            this.pater = ''
            this.grandsire = ''
            this.userInfo = []
            this.LowerUser = []
            this.pointsList = []
            var user = {
                pater: '',
                grandsire: '',
                surplusPoint: '',
                note: 0
            }
            this.getHeight(user, userId)

            listLowerUser({
                userId
            }).then(res => {
                if (res.flag) {
                    user.note = res.data.user.note
                    this.LowerUser.push(...res.data.xj)
                    this.LowerUser.push(...res.data.xxj)

                }
            })


            this.dialogVisible = true
        },

        // 

        getHeight(user, userId) {

            console.log(this.userInfo);
            console.log(this.LowerUser);
            console.log(userId);

            listHigherUser({
                userId
            }).then(res => {
                if (res.flag) {
                    user.pater = res.data.pater != null ? res.data.pater : ''
                    user.grandsire = res.data.grandsire != null ? res.data.grandsire : ''
                    console.log(user);
                }
            })
            listPoints({
                userId
            }).then(res => {
                if (res.flag) {
                    user.surplusPoint = res.data.remainingTotalScore
                    res.data.notExpired.forEach(item => {
                        item.isPass = false
                        this.pointsList.push(item)
                    })
                    res.data.transferOut.forEach(item => {
                        item.isPass = false
                        this.pointsList.push(item)
                    })
                    res.data.isExpired.forEach(item => {
                        item.isPass = false
                        this.pointsList.push(item)
                    })

                    this.pointsList = this.pointsList.sort((a, b) => {
                        return b.pointId - a.pointId
                    })

                    console.log(this.pointsList);
                }
            })
            this.userInfo.push(user)
        },

        getList() {
            selectUser({
                flag: this.searchInput == '' ? -1 : this.searchType,
                name: this.searchType == 1 ? this.searchInput : 0,
                id: this.searchInput == '' ? 0 : this.searchType == 0 ? this.searchInput : 0,
            }).then((res) => {
                console.log(res);
                if (res.flag) {
                    this.tableData = res.data
                }
            });
        },
        //校验用户信息
        checkHandle(id) {
            if (id == '') {
                this.$message.warning('请输入受赠人ID')
                return
            }
            selectUser({
                flag: 0,
                name: 0,
                id,
            }).then((res) => {
                console.log(res);
                if (res.flag) {

                    this.checkFlag = res.data.length != 0 ? 1 : 2
                    this.checkUserInfo = res.data[0]
                }
            });
        },

        //每页条数改变
        handleSizeChange(val) {
            this.pageSize = val;
            this.getList();
        },
        //页数改变
        handleCurrentChange(val) {
            this.pageNumber = val;
            this.getList();
        },
    },
    created() {
        this.getList();
    },
};
</script>

<style scoped>
.titleBox {
    margin: 20px 0;
    font-size: 16px;
    color: #333;
    font-weight: bold;
}

.search-select {
    width: 100px;
}


.checkSuccess {
    font-size: 14px;
    color: #409EFF;
}

.checkError {
    font-size: 14px;
    color: #F56C6C;
}
</style>